<template>
  <div class="product-management">
    <!-- 搜索表单 -->
    <a-card>
      <a-form style="width: 100%;" layout="inline" :label-col="{ style: { width: '80px', textAlign: 'left' } }"
        :model="searchForm" @finish="handleSearch">
        <div class="user-form">
          <a-row :gutter="[16, 16]" style="flex: 1;">
            <a-col class="gutter-row" :span="8">
              <a-form-item label="订单状态">
                <a-select v-model:value="searchForm.order_status" allowClear>
                  <a-select-option value="">全部订单</a-select-option>
                  <a-select-option :value="1">待付款</a-select-option>
                  <a-select-option :value="2">待发货</a-select-option>
                  <a-select-option :value="3">待收货</a-select-option>
                  <a-select-option :value="4">待评价</a-select-option>
                  <a-select-option :value="5">已取消</a-select-option>
                  <a-select-option :value="6">已评价</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <div class="form-btn">
            <a-form-item>
              <a-button type="primary" html-type="submit">搜索</a-button>
            </a-form-item>
          </div>
        </div>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card style="margin-top: 16px" class="table-body">
      <div class="table-contaier" ref="tableContainerRef">
        <a-table :scroll="{ y: tableHeight + 'px' }" :loading="loading" :columns="columns" :data-source="orderList"
          :pagination="pagination" row-key="order_id" @change="handleTableChange">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'index'">
              {{ index + 1 }}
            </template>
            <template v-if="column.key === 'order_status'">
              {{ getStatusText(record.order_status) }}
            </template>
            <template v-if="column.key === 'user_name'">
              {{ record.user.username }}
            </template>
            <template v-if="column.key === 'address'">
              {{ formatAddress(record.user.address) }}
            </template>
            <template v-if="column.key === 'order_amount'">
              {{ Number(record.order_amount).toFixed(2) }}
            </template>
            <template v-if="column.key === 'create_time'">
              {{ record.create_time ? formatTime(record.create_time) : '' }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" v-if="![4,5,6].includes(record.order_status)" @click="handleCancel(record)">取消订单</a-button>
                <a-button type="link" v-if="record.order_status === 2" @click="handleConfirm(record)">确认发货</a-button>
              </a-space>
            </template>
          </template>
          <template #expandedRowRender="{ record }">
            <a-table style="padding: 10px;" :columns="productColumns" :data-source="record.productList ?? []"
              :pagination="false" row-key="user_id">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'index'">
                  {{ index + 1 }}
                </template>
                <template v-if="column.key === 'image'">
                  <a-image :width="40" :src="record.image"
                    fallback="" />
                </template>
                <template v-if="column.key === 'type'">
                  {{ formatType(record.type) }}
                </template>
                <template v-if="column.key === 'mark'">
                  {{ formatMark(record.mark) }}
                </template>
                <template v-if="column.key === 'state'">
                  {{ formatState(record.state) }}
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  message,
  Modal
} from 'ant-design-vue'
import {
  PlusOutlined,
  DownloadOutlined,
  DownOutlined,
  DeleteOutlined,
  UnlockOutlined,
  LockOutlined
} from '@ant-design/icons-vue';
import moment from 'moment';
import md5 from 'md5-node';
import { queryAllOrder, updateOrder, removeOrder } from '@/apis/admin/order'
import upload from '../../../components/upload.vue'
import { codeToText } from 'element-china-area-data';
export default {
  components: {
    PlusOutlined,
    DownloadOutlined,
    DownOutlined,
    DeleteOutlined,
    UnlockOutlined,
    LockOutlined,
    upload
  },
  setup() {
    // 数据状态
    const orderList = ref([])
    const loading = ref(false)
    const selectedRowKeys = ref([])

    const tableContainerRef = ref();
    const tableHeight = ref(600);
    onMounted(() => {
      tableHeight.value = tableContainerRef.value.clientHeight - 88;
    })



    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 8,
      total: 0,
      showSizeChanger: false,
      showTotal: total => `总共 ${total} 条`
    })

    // 搜索表单
    const searchForm = reactive({
      order_status: '',
    })


    // 表格列配置
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width:'100px',
        key: 'index',
      },
      {
        title: '订单号',
        dataIndex: 'order_no',
        width:'140px',
        key: 'order_no'
      },

      {
        title: '用户ID',
        dataIndex: 'user_id',
        width:'100px',
        key: 'user_id'
      },
      {
        title: '用户名称',
        dataIndex: 'user_name',
        width:'140px',
        key: 'user_name'
      },
      {
        title: '订单地址',
        dataIndex: 'address',
        width:'240px',
        key: 'address'
      },
      {
        title: '订单时间',
        dataIndex: 'create_time',
        width:'200px',
        key: 'create_time'
      },
      {
        title: '订单金额',
        dataIndex: 'order_amount',
        width:'100px',
        key: 'order_amount'
      },
      {
        title: '订单状态',
        dataIndex: 'order_status',
        width:'100px',
        key: 'order_status'
      },
      {
        title: '操作',
        key: 'action',
        width:'250px',
        fixed:'right'
      }
    ]

    const productColumns = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '外卖图片',
        dataIndex: 'image',
        key: 'image'
      },
      {
        title: '外卖名称',
        dataIndex: 'title',
        key: 'title'
      },
      {
        title: '外卖描述',
        dataIndex: 'spec',
        key: 'spec'
      },
      {
        title: '价格(元)',
        key: 'originalPrice',
        dataIndex: 'originalPrice'
      },
      {
        title: '折后价(元)',
        key: 'price',
        dataIndex: 'price'
      },
      {
        title: '数量',
        key: 'quantity',
        dataIndex: 'quantity'
      },
    ]

    // 生命周期钩子
    onMounted(() => {
      fetchOrderList()
    })

    // 方法
    const fetchOrderList = async () => {
      try {
        loading.value = true

        const params = {
          page: pagination.current,
          limit: pagination.pageSize,
          ...searchForm,
        }
        for (let keys in params) {
          if (params[keys] === null || params[keys] === undefined || params[keys] === '') delete params[keys]
        }

        const res = await queryAllOrder(params)
        if (res.code === 0) {
          orderList.value = res.data.list.map(item => {
            return {
              ...item,
              productList: JSON.parse(item.product)
            }
          })
          console.log(orderList.value);

          pagination.total = res.data.total
        } else {
          message.error(res.message)
        }
      } catch (error) {
        message.error('获取产品列表失败')
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      fetchOrderList()
    }

    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        if (Array.isArray(searchForm[key])) {
          searchForm[key] = []
        } else {
          searchForm[key] = undefined
        }
      })
      handleSearch()
    }

    const handleTableChange = (pag, filters, sorter) => {
      pagination.current = pag.current
      pagination.pageSize = pag.pageSize
      fetchOrderList()
    }





    const confirmDelete = async (record) => {
      const res = await delProduct(record.product_id)
      if (res.code === 0) {
        message.success('删除成功')
        fetchOrderList()
      } else {
        message.error(res.message)
      }
    }

    // 获取订单状态文本
    const getStatusText = (status) => {
      const statusMap = ['全部', '待付款', '待发货', '待收货', '待评价', '已取消','已评价'];
      return statusMap[status] || '';
    };

    // 格式化时间
    const formatTime = (time) => {
      return moment(time).format('YYYY-MM-DD HH:mm:ss');
    };

    const formatAddress = (address) => {
      let addr = '';
      let region = [];
      if (address) {
        address = JSON.parse(address);
        if (Array.isArray(address) && address.length >= 4) {
          region = address.slice(0, 3);
          addr = address.slice(3, 4)
        }
      }
      return region.length >= 3 ? convertCodesToText(region) + ' ' + addr : addr;
    }
    function convertCodesToText(codes) {
      return codes.map(code => {
        return codeToText[code] || '未知地区'
      }).join(' ')
    }

    function formatType(type) {
      if (type === 1) {
        return '主食'
      } else if (type === 2) {
        return '饮料'
      } else if (type === 3) {
        return '小吃'
      } else if (type === 4) {
        return '水果'
      } else {
        return ''
      }
    }

    function formatState(state) {
      if (state === 1) {
        return '上架'
      } else {
        return '未上架'
      }
    }

    function formatMark(mark) {
      if (mark === 1) {
        return '新品'
      } else if (mark === 2) {
        return '招牌'
      } else if (mark === 3) {
        return '推荐'
      } else {
        return '推荐'
      }
    }

    const handleConfirm = (order) => {
      message.success(`确认发货: ${order.order_no}`);
      // 实际调用确认收货API
      handleOrderStatus(order.order_id, 3)
    };

    const handleCancel = (order) => {
      Modal.confirm({
        title: `你确定要取消该订单？订单号:${order.order_no}`,
        content: '',
        centered: true,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 实际调用取消订单API
          handleOrderStatus(order.order_id, 5)
          message.success(`取消订单: ${order.order_no}`);
        }
      });
    };

    const handleOrderStatus = (id, status) => {
      updateOrder(id, {
        order_status: status
      }).then((res) => {
        if (res.code === 0) {
          fetchOrderList();
        }
      })
    }

    return {
      formatType,
      formatState,
      formatMark,
      getStatusText,
      formatTime,
      // 状态
      orderList,
      loading,
      selectedRowKeys,
      pagination,
      handleConfirm,

      tableContainerRef,
      tableHeight,
      formatAddress,
      // 表单数据
      searchForm,
      confirmDelete,
      handleCancel,

      // 配置
      columns,
      productColumns,
      // 方法
      handleSearch,
      resetSearch,
      handleTableChange,
    }
  }
}
</script>

<style lang="less" scoped>
.product-management {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .user-form {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .form-btn {
      min-width: 140px;
    }
  }

  .table-body {
    flex: 1;

    :deep(.ant-card-body) {
      height: 100%;
      display: flex;
      flex-direction: column;

      .table-contaier {
        flex: 1;

        .ant-table {
          height: 100%;
        }
      }

    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.ant-card {
  margin-bottom: 16px;
}
</style>